"use client"

import type React from "react"

import { useState, useEffect, useRef } from "react"
import Image from "next/image"
import { Button } from "@/components/ui/button"
import { Card, CardContent } from "@/components/ui/card"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import { toast } from "@/components/ui/use-toast"
import Sidebar from "@/components/sidebar"
import { fetchSignatures, uploadSignature, deleteSignature } from "@/lib/api"

interface Signature {
  id: string
  imageUrl: string
  createdAt: string
}

export default function SignatureDataPage() {
  const [signatures, setSignatures] = useState<Signature[]>([])
  const [loading, setLoading] = useState(true)
  const [uploadingFile, setUploadingFile] = useState(false)
  const [uploadingCanvas, setUploadingCanvas] = useState(false)
  const [isDrawing, setIsDrawing] = useState(false)
  const [confirmDelete, setConfirmDelete] = useState<string | null>(null)

  const canvasRef = useRef<HTMLCanvasElement>(null)
  const ctxRef = useRef<CanvasRenderingContext2D | null>(null)

  useEffect(() => {
    loadSignatures()
    initCanvas()
  }, [])

  const loadSignatures = async () => {
    try {
      const data = await fetchSignatures()
      setSignatures(data)
    } catch (error) {
      console.error("Failed to load signatures:", error)
      toast({
        title: "加载失败",
        description: "无法加载签名数据，请稍后再试",
        variant: "destructive",
      })
    } finally {
      setLoading(false)
    }
  }

  const initCanvas = () => {
    const canvas = canvasRef.current
    if (!canvas) return

    canvas.width = canvas.offsetWidth
    canvas.height = canvas.offsetHeight

    const ctx = canvas.getContext("2d")
    if (!ctx) return

    ctx.lineWidth = 3
    ctx.lineCap = "round"
    ctx.strokeStyle = "black"
    ctxRef.current = ctx
  }

  const startDrawing = (e: React.MouseEvent<HTMLCanvasElement>) => {
    const ctx = ctxRef.current
    if (!ctx) return

    const rect = canvasRef.current?.getBoundingClientRect()
    if (!rect) return

    ctx.beginPath()
    ctx.moveTo(e.clientX - rect.left, e.clientY - rect.top)
    setIsDrawing(true)
  }

  const draw = (e: React.MouseEvent<HTMLCanvasElement>) => {
    if (!isDrawing) return

    const ctx = ctxRef.current
    if (!ctx) return

    const rect = canvasRef.current?.getBoundingClientRect()
    if (!rect) return

    ctx.lineTo(e.clientX - rect.left, e.clientY - rect.top)
    ctx.stroke()
  }

  const endDrawing = () => {
    const ctx = ctxRef.current
    if (!ctx) return

    ctx.closePath()
    setIsDrawing(false)
  }

  const clearCanvas = () => {
    const canvas = canvasRef.current
    const ctx = ctxRef.current
    if (!canvas || !ctx) return

    ctx.clearRect(0, 0, canvas.width, canvas.height)
  }

  const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (!file) return

    setUploadingFile(true)
    try {
      await uploadSignature(file)
      loadSignatures()
      toast({
        title: "上传成功",
        description: "签名图片已成功上传",
      })
    } catch (error) {
      console.error("Failed to upload signature:", error)
      toast({
        title: "上传失败",
        description: "无法上传签名图片，请稍后再试",
        variant: "destructive",
      })
    } finally {
      setUploadingFile(false)
      // 清空文件输入
      e.target.value = ""
    }
  }

  const saveCanvasSignature = async () => {
    const canvas = canvasRef.current
    if (!canvas) return

    // 检查画布是否为空
    const ctx = ctxRef.current
    if (!ctx) return

    const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height).data
    const isCanvasBlank = !imageData.some((channel) => channel !== 0)

    if (isCanvasBlank) {
      toast({
        title: "保存失败",
        description: "签名不能为空，请先在画布上绘制签名",
        variant: "destructive",
      })
      return
    }

    setUploadingCanvas(true)
    try {
      // 将画布内容转换为 Blob
      const blob = await new Promise<Blob>((resolve) => {
        canvas.toBlob((blob) => {
          if (blob) resolve(blob)
          else throw new Error("Failed to convert canvas to blob")
        }, "image/png")
      })

      // 创建文件对象
      const file = new File([blob], "signature.png", { type: "image/png" })

      await uploadSignature(file)
      loadSignatures()
      clearCanvas()
      toast({
        title: "保存成功",
        description: "签名已成功保存",
      })
    } catch (error) {
      console.error("Failed to save canvas signature:", error)
      toast({
        title: "保存失败",
        description: "无法保存签名，请稍后再试",
        variant: "destructive",
      })
    } finally {
      setUploadingCanvas(false)
    }
  }

  const handleDelete = async (id: string) => {
    try {
      await deleteSignature(id)
      setSignatures(signatures.filter((sig) => sig.id !== id))
      toast({
        title: "删除成功",
        description: "签名已成功删除",
      })
    } catch (error) {
      console.error("Failed to delete signature:", error)
      toast({
        title: "删除失败",
        description: "无法删除签名，请稍后再试",
        variant: "destructive",
      })
    } finally {
      setConfirmDelete(null)
    }
  }

  const handleDownload = (url: string, filename: string) => {
    const a = document.createElement("a")
    a.href = url
    a.download = filename || "signature.png"
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
  }

  return (
    <div className="flex h-screen bg-gray-100">
      <Sidebar />

      <main className="flex-1 p-8 overflow-y-auto">
        <h2 className="text-3xl font-bold mb-6">签名数据维护</h2>

        {/* 显示已有签名图片 */}
        <div>
          <h3 className="text-2xl font-semibold mb-4">已上传签名样本</h3>

          {loading ? (
            <div className="flex justify-center items-center h-40">
              <div className="animate-spin rounded-full h-10 w-10 border-b-2 border-primary"></div>
            </div>
          ) : signatures.length > 0 ? (
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
              {signatures.map((signature) => (
                <Card key={signature.id} className="flex flex-col items-center p-4">
                  <div className="relative w-40 h-40 mb-2">
                    <Image
                      src={signature.imageUrl || "/placeholder.svg"}
                      alt={`签名 ${signature.id}`}
                      fill
                      className="object-contain rounded-lg"
                    />
                  </div>
                  <CardContent className="p-0 w-full flex justify-center space-x-2 mt-2">
                    <Button
                      size="sm"
                      variant="outline"
                      className="bg-blue-500 text-white hover:bg-blue-600"
                      onClick={() => handleDownload(signature.imageUrl, `signature_${signature.id}.png`)}
                    >
                      <svg
                        xmlns="http://www.w3.org/2000/svg"
                        className="h-4 w-4 mr-1"
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        strokeWidth="2"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                      >
                        <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
                        <polyline points="7 10 12 15 17 10"></polyline>
                        <line x1="12" y1="15" x2="12" y2="3"></line>
                      </svg>
                      下载
                    </Button>

                    <Dialog>
                      <DialogTrigger asChild>
                        <Button size="sm" variant="outline" className="bg-red-500 text-white hover:bg-red-600">
                          <svg
                            xmlns="http://www.w3.org/2000/svg"
                            className="h-4 w-4 mr-1"
                            viewBox="0 0 24 24"
                            fill="none"
                            stroke="currentColor"
                            strokeWidth="2"
                            strokeLinecap="round"
                            strokeLinejoin="round"
                          >
                            <polyline points="3 6 5 6 21 6"></polyline>
                            <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
                            <line x1="10" y1="11" x2="10" y2="17"></line>
                            <line x1="14" y1="11" x2="14" y2="17"></line>
                          </svg>
                          删除
                        </Button>
                      </DialogTrigger>
                      <DialogContent>
                        <DialogHeader>
                          <DialogTitle>确认删除</DialogTitle>
                          <DialogDescription>您确定要删除这个签名样本吗？此操作无法撤销。</DialogDescription>
                        </DialogHeader>
                        <div className="py-4 flex justify-center">
                          <div className="relative w-40 h-40">
                            <Image
                              src={signature.imageUrl || "/placeholder.svg"}
                              alt={`签名 ${signature.id}`}
                              fill
                              className="object-contain rounded-lg"
                            />
                          </div>
                        </div>
                        <DialogFooter>
                          <Button variant="outline" onClick={() => setConfirmDelete(null)}>
                            取消
                          </Button>
                          <Button variant="destructive" onClick={() => handleDelete(signature.id)}>
                            确认删除
                          </Button>
                        </DialogFooter>
                      </DialogContent>
                    </Dialog>
                  </CardContent>
                </Card>
              ))}
            </div>
          ) : (
            <Card className="p-8 text-center">
              <p className="text-gray-500">暂无签名样本，请上传或绘制您的签名</p>
            </Card>
          )}
        </div>

        {/* 新增签名 */}
        <div className="mt-8">
          <h3 className="text-2xl font-semibold mb-4">新增签名样本</h3>
          <div className="space-y-6">
            <Card className="p-6">
              <h4 className="text-xl font-medium mb-2">上传本地图片</h4>
              <input
                type="file"
                id="uploadSignature"
                accept="image/*"
                onChange={handleFileUpload}
                className="p-2 border border-gray-300 rounded-md w-full"
                disabled={uploadingFile}
              />
              {uploadingFile && <p className="mt-2 text-sm text-gray-600">上传中，请稍候...</p>}
            </Card>

            <Card className="p-6">
              <h4 className="text-xl font-medium mb-2">在网页上绘制签名</h4>
              <div className="border-2 border-gray-300 w-full h-48 rounded-md mb-4 bg-white">
                <canvas
                  ref={canvasRef}
                  className="w-full h-full cursor-crosshair"
                  onMouseDown={startDrawing}
                  onMouseMove={draw}
                  onMouseUp={endDrawing}
                  onMouseLeave={endDrawing}
                />
              </div>

              <div className="flex justify-center space-x-4">
                <Button
                  onClick={saveCanvasSignature}
                  className="bg-green-500 hover:bg-green-600"
                  disabled={uploadingCanvas}
                >
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    className="h-5 w-5 mr-1"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                  >
                    <path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"></path>
                    <polyline points="17 21 17 13 7 13 7 21"></polyline>
                    <polyline points="7 3 7 8 15 8"></polyline>
                  </svg>
                  保存
                </Button>
                <Button
                  onClick={clearCanvas}
                  variant="outline"
                  className="bg-yellow-500 text-white hover:bg-yellow-600"
                  disabled={uploadingCanvas}
                >
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    className="h-5 w-5 mr-1"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                  >
                    <path d="M18 6L6 18"></path>
                    <path d="M6 6l12 12"></path>
                  </svg>
                  清空重写
                </Button>
              </div>

              {uploadingCanvas && <p className="mt-2 text-sm text-gray-600 text-center">保存中，请稍候...</p>}
            </Card>
          </div>
        </div>
      </main>
    </div>
  )
}
